package com.keson.spider;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.ProxyConfig;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.util.Cookie;


/**
 * Hello world!
 *
 */
public class App {
    private static String indexUrl = "http://10.13.24.50/index.jsp";
    private static String searchUrl = "http://10.13.24.50/search.jsp?Cname1=HE&Message_type1=0x10022&ReceiveFrom=&ReceiveTo=&O_timeFrom=&O_timeTo=&LonFrom=&LonTo=&LatFrom=&LatTo=&MFrom=0&MTo=10&paixu=1&Submit=%B2%E9%D1%AF";
		
	private static String uname = "HETS";
	private static String psw = "HETS";
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

	public static void main( String[] args ){
		try {
			//创建一个webclient
			WebClient webClient = new WebClient(BrowserVersion.CHROME); 
			
			//参数设置
			// 1 启动JS
			webClient.getOptions().setJavaScriptEnabled(true);
			// 2 禁用Css，可避免自动二次请求CSS进行渲染
			webClient.getOptions().setCssEnabled(false);
			//3 启动客户端重定向
			webClient.getOptions().setRedirectEnabled(true);
			// 4 运行错误时，是否抛出异常
			webClient.getOptions().setThrowExceptionOnScriptError(false);
			// 5 设置超时
			webClient.getOptions().setTimeout(50000);
			//6 设置忽略证书
			//webClient.getOptions().setUseInsecureSSL(true);
			//7 设置Ajax
			//webClient.setAjaxController(new NicelyResynchronizingAjaxController());
			//8设置cookie
			webClient.getCookieManager().setCookiesEnabled(true);
			
			//获取页面
			HtmlPage page = webClient.getPage(indexUrl);  
			// 根据form的名字获取页面表单，也可以通过索引来获取：page.getForms().get(0)   
	        HtmlForm form = page.getForms().get(0);       
	        HtmlTextInput username = (HtmlTextInput) form.getInputByName("userid");
	        HtmlPasswordInput password = (HtmlPasswordInput) form.getInputByName("password");
	        username.setValueAttribute(uname);
	        password.setValueAttribute(psw);
	        HtmlSubmitInput button = page.getElementByName("Submit");   
	        HtmlPage retPage = (HtmlPage) button.click();
			// 等待JS驱动dom完成获得还原后的网页
			webClient.waitForBackgroundJavaScript(10000);
			//获取cookie
			Set<Cookie> cookies = webClient.getCookieManager().getCookies();; 
			HashMap<String, String> responseCookies = new HashMap<String, String>();
			for (Cookie c : cookies) {
				responseCookies.put(c.getName(), c.getValue());
				System.out.println(c.getName()+":"+c.getValue());
			}
			
			//定时获取
			JSONObject json = new JSONObject();
			File msgfile = new File("cache/msg.txt");
			if(!msgfile.exists()) {
				msgfile.getParentFile().mkdirs();
				msgfile.createNewFile();
			}
			String idCache = FileUtil.readFileContent(msgfile);
			System.out.println("登录成功，请勿关闭窗口！！！");
			System.out.println("登录成功，请勿关闭窗口！！！");
			System.out.println("登录成功，请勿关闭窗口！！！");
			System.out.println("登录成功，请勿关闭窗口！！！");
			System.out.println("登录成功，请勿关闭窗口！！！");
			System.out.println("消息监控中...");
			while(true) {
				try {
					page = webClient.getPage(searchUrl);
					webClient.waitForBackgroundJavaScript(10000);
					
					DomNodeList<HtmlElement> tds = page.getElementsByTagName("tr").get(1).getElementsByTagName("td");
//		          {"1":"20200106143827_1424_1","2":"0401","3":"20200106143827_1424_1","4":"云南省昆明市安宁市","5":"25.020","6":"102.353","7":"20","8":"6.1","9":"2020-02-01 15:36:20"}
					
					if(!idCache.equals(tds.get(0).asNormalizedText().trim()) ) {
						json.put("1", tds.get(0).asNormalizedText().trim());//消息ID
						json.put("2", "0401");								//消息类型
						json.put("3", tds.get(0).asNormalizedText().trim());//地震事件ID
						json.put("4", tds.get(9).asNormalizedText().trim());//地名
						json.put("5", tds.get(3).asNormalizedText().trim());//震中纬度
						json.put("6", tds.get(4).asNormalizedText().trim());//震中经度
						json.put("7", tds.get(5).asNormalizedText().trim());//深度
						json.put("8", tds.get(6).asNormalizedText().trim());//震级
						json.put("9", tds.get(2).asNormalizedText().trim());//发震时刻
						MqttClientUtil.publishTopic("EQR/JSON", 2, json.toJSONString(), false);
						
						idCache = tds.get(0).asNormalizedText().trim();
						FileUtil.writeFileContent(msgfile, idCache);
						
						float magnitude = Float.parseFloat(tds.get(6).asNormalizedText().trim());
						float lon = Float.parseFloat(tds.get(4).asNormalizedText().trim());
						float lat = Float.parseFloat(tds.get(3).asNormalizedText().trim());
						
						if((magnitude>=2&&lon>=115.7&&lon<=121&&lat>=38.9&&lat<=41.8)
								||(magnitude>=5&&lon>=113.3&&lon<=120&&lat>=36&&lat<=43)
								||(magnitude>=6&&lon>=73.7&&lon<=135.1&&lat>=4&&lat<=53.5)
								||(magnitude>=5&&lon>=120&&lon<=121&&lat>=37.8&&lat<=38.9)) {
							
							HashMap<String, String> map = new HashMap<String, String>();
							Date date = sdf.parse(tds.get(2).asNormalizedText().trim());
							Calendar c = Calendar.getInstance();
							c.setTime(date);
					    	map.put("index", " ");//序号
					    	map.put("sname", "    ");//姓名
					    	map.put("y", c.get(Calendar.YEAR)+"");
					    	map.put("mo", c.get(Calendar.MONTH)+1+"");
					    	map.put("d", c.get(Calendar.DAY_OF_MONTH)+"");
					    	map.put("h", c.get(Calendar.HOUR_OF_DAY)+"");
					    	map.put("mi", c.get(Calendar.MINUTE)+"");
					    	map.put("l", tds.get(9).asNormalizedText().trim());
					    	map.put("ma", magnitude+"");
					    	map.put("lat", lat+"");
					    	map.put("lon", lon+"");
					    	map.put("dep", tds.get(5).asNormalizedText().trim());
					    	map.put("wname", "    ");//姓名2
					    	map.put("ename", "    ");//姓名3
					    	DocUtil.build("template/word.doc",map,"doc/第1期（第一次）.doc");
					    	
					    	WordPrintUtil.print("doc/第1期（第一次）.doc");
						}
						
						System.out.println("请勿关闭窗口！！！");
					}
					
					//关闭webclient
//					webClient.close(); 	
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				Thread.sleep(10000);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
    }
	
//	public static void main(String[] args) {
//		try {
//			Document document = Jsoup.connect("https://www.chazhengla.com/xianxing/tangshan/").get();
//			Elements tds = document.getElementById("result").getElementsByTag("td");
//			int now = 0;
//			for (int i = 0; i < tds.size(); i++) {
//				if(!"".equals(tds.get(i).attr("style"))) {
//					now = i;
//					break;
//				}
//			}
//			
//			System.out.println(tds.get(now).text());
//			System.out.println(tds.get(now==6?0:(now+1)).text());
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
}
